package com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.review

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.helasasa.maxfunds.lineofcredit.cashloan.ProjectApplication
import com.helasasa.maxfunds.lineofcredit.cashloan.R
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.http.hitPointCameroon
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.proof.wallet.ProofCameroonWalletActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.review.subview.IReviewCameroonWalletAddDialogListener
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.review.subview.ReviewCameroonNewUserDialog
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.review.subview.ReviewCameroonOldUserDialog
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.review.subview.ReviewCameroonWalletAddDialog
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.subview.HotlineCameroonDialog
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.tabrepay.TabRepayCameroonActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.databinding.ActivityCameroonReviewBinding
import org.json.JSONObject

class ReviewCameroonActivity : AppCompatActivity() {

    private lateinit var reviewViewModel: ReviewCameroonViewModel
    private lateinit var binding: ActivityCameroonReviewBinding
    private lateinit var adapter: ReviewCameroonPageAdapter
    private lateinit var walletAdapter: ReviewCameroonWalletAdapter
    private lateinit var boldDialog: ReviewCameroonNewUserDialog
    private lateinit var normalDialog: ReviewCameroonOldUserDialog
    private lateinit var walletAddDialog: ReviewCameroonWalletAddDialog

    @SuppressLint("NotifyDataSetChanged", "ResourceType")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 数据模型
        reviewViewModel = ViewModelProvider(this)[ReviewCameroonViewModel::class.java]

        // 关联布局
        binding = ActivityCameroonReviewBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 用到的控件
        val back = binding.navbarLeft
        val hotline = binding.navbarRight
        val loading = binding.loading
        val list = binding.list
        val walletList = binding.walletList
        val addWalletBg = binding.addWalletBg
        val refresh = binding.refresh

        // 初始化下拉刷新
        refresh.apply {
            setColorSchemeColors(Color.parseColor("#5277D6"))

            setOnRefreshListener { reviewViewModel.pageDetail() }
        }

        // 初始化adapter
        adapter = ReviewCameroonPageAdapter(emptyList())
        list.layoutManager = LinearLayoutManager(this)
        list.adapter = adapter

        // 初始化adapter
        walletAdapter = ReviewCameroonWalletAdapter(emptyList())
        walletList.layoutManager = LinearLayoutManager(this)
        walletList.adapter = walletAdapter

        // 初始化add wallet dialog
        walletAddDialog =
            ReviewCameroonWalletAddDialog(object : IReviewCameroonWalletAddDialogListener {
                override fun onClick(type: Int) {
                    addWalletBg.performClick()
                }
            })

        // 页面loading状态接口监听
        reviewViewModel.loadingResult.observe(this@ReviewCameroonActivity, Observer {
            val loadingResult = it ?: return@Observer

            if (loadingResult) {
                loading.visibility = View.VISIBLE
            } else {
                refresh.isRefreshing = false
                loading.visibility = View.GONE
            }
        })

        // 页面详情接口监听
        reviewViewModel.pageDetailResult.observe(this@ReviewCameroonActivity, Observer {
            val pageDetailResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (pageDetailResult.error != null) {
                showMessage(pageDetailResult.error)
            }
            if (pageDetailResult.success != null) {
                binding.loanAmount.text = pageDetailResult.success.optString("amountFormat")
                binding.loanTerm.text = pageDetailResult.success.optString("daysFormat")
            }
        })

        // 评价接口监听
        reviewViewModel.reviewDialogResult.observe(this@ReviewCameroonActivity, Observer {
            val reviewDialogResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (reviewDialogResult.error != null) {
                showMessage(reviewDialogResult.error)
            }
            if (reviewDialogResult.boldDialog != null) {
                boldDialog.setDialogContent(reviewDialogResult.boldDialog)
                boldDialog.showNow(supportFragmentManager, "ReviewDialog")

            } else if (reviewDialogResult.normalDialog != null) {
                normalDialog.setDialogContent(reviewDialogResult.normalDialog)
                normalDialog.showNow(supportFragmentManager, "ReviewDialog")
            }
        })

        // 卡列表接口监听
        reviewViewModel.walletListResult.observe(this@ReviewCameroonActivity, Observer {
            val walletListResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (walletListResult.error != null) {
                showMessage(walletListResult.error)
            }

            // 渲染已绑列表
            if (walletListResult.items != null) {
                walletAdapter.dataList = walletListResult.items
                walletAdapter.notifyDataSetChanged()
            }

            if (walletListResult.showAdd == true) {
                walletAddDialog.showNow(supportFragmentManager, "walletInfo")
            }
        })

        // 推荐产品列表接口监听
        reviewViewModel.commendProductsResult.observe(this@ReviewCameroonActivity, Observer {
            val commendProductsResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (commendProductsResult.error != null) {
                showMessage(commendProductsResult.error)
            }
            if (commendProductsResult.success != null) {
                adapter.dataList = commendProductsResult.success
                adapter.notifyDataSetChanged()
                if (commendProductsResult.success.isEmpty()) {
                    binding.recommendBg.visibility = View.GONE
                } else {
                    binding.recommendBg.visibility = View.VISIBLE
                }
            }
        })

        // 点击申请
        back.setOnClickListener {
            startNextActivity(TabRepayCameroonActivity::class.java)
        }

        // 点击客服
        hotline.setOnClickListener {
            // 客服弹框
            HotlineCameroonDialog().showNow(supportFragmentManager, "hotline")
            hitPointCameroon("SHOW_HOTLINE")
        }

        // 点击增加卡
        addWalletBg.setOnClickListener {
            hitPointCameroon("REVIEW_ADD_WALLET_CLICK")
            val intent =
                Intent(this@ReviewCameroonActivity, ProofCameroonWalletActivity::class.java)
            startActivity(intent)
        }

        // 查询页面详情
        reviewViewModel.pageDetail()

        // 查询卡列表
        reviewViewModel.walletList()

        // 查询产品列表
        reviewViewModel.commendProducts()
    }

    override fun onResume() {
        super.onResume()
        hitPointCameroon(type = this::class.java.simpleName, isPageStart = true)
    }

    override fun onPause() {
        super.onPause()
        hitPointCameroon(type = this::class.java.simpleName, isPageEnd = true)
    }
}

class ReviewCameroonPageAdapter(
    var dataList: List<JSONObject>
) :
    RecyclerView.Adapter<ReviewCameroonPageAdapter.ViewHolder>() {

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int,
    ): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.view_cameroon_disbursing_activity_adapter, parent, false)
        return ViewHolder(view)
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        private val icon: ImageView = view.findViewById(R.id.icon)
        private val name: TextView = view.findViewById(R.id.name)
        private val amount: TextView = view.findViewById(R.id.amount)
        private val star: TextView = view.findViewById(R.id.star)
        private val download: TextView = view.findViewById(R.id.download)
        private val installBg: LinearLayout = view.findViewById(R.id.installBg)

        fun bindData(item: JSONObject) {
            val product = item.optString("product")
            name.text = item.optString("appName")
            amount.text = item.optString("appLoanAmount")
            star.text = item.optString("star")
            download.text = item.optString("download")

            val logo = item.optString("appLogo")
            if (logo.isNotBlank()) {
                icon.visibility = View.VISIBLE
                Glide.with(icon).load(logo).into(icon)
            } else {
                icon.visibility = View.GONE
            }

            val link = item.optString("appLink")
            installBg.setOnClickListener {
                if (link.isNotBlank()) {
                    installBg.context.hitPointCameroon("DC_INSTALL_CLICK", product)

                    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(link)).apply {
                        flags = Intent.FLAG_ACTIVITY_NEW_TASK
                    }
                    if (intent.resolveActivity(ProjectApplication.instance.packageManager) != null) {
                        ProjectApplication.instance.startActivity(intent)
                    } else {
                        ProjectApplication.instance.startActivity(
                            Intent.createChooser(intent, "Please select a browser to open")
                        )
                    }
                }
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val data: JSONObject = dataList[position]
        holder.bindData(data)
    }

    override fun getItemCount(): Int {
        return dataList.size
    }
}

fun Context.showMessage(message: String) {
    Toast.makeText(applicationContext, message, Toast.LENGTH_SHORT).show()
}

fun Context.startNextActivity(
    activity: Class<out AppCompatActivity>? = null,
    params: HashMap<String, String> = HashMap()
) {
    val nextActivity = activity ?: return
    try {
        val intent = Intent(this, nextActivity)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
        params.keys.forEach { gKey ->
            intent.putExtra(gKey, params[gKey])
        }
        startActivity(intent)
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

class ReviewCameroonWalletAdapter(
    var dataList: List<JSONObject>
) : RecyclerView.Adapter<ReviewCameroonWalletAdapter.ViewHolder>() {

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int,
    ): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.view_cameroon_review_wallet_activity_adapter, parent, false)
        return ViewHolder(view)
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        private val title: TextView = view.findViewById(R.id.title)
        private val icon: ImageView = view.findViewById(R.id.icon)
        private val type: TextView = view.findViewById(R.id.type)
        private val account: TextView = view.findViewById(R.id.account)

        @SuppressLint("SetTextI18n")
        fun bindData(item: JSONObject, position: Int) {
            title.text = "Portefeuille mobile ${position + 1}"
            type.text = item.optString("walletDesc")
            account.text = item.optString("walletMobile")

            val logo = item.optString("walletLogo")
            if (logo.isNotBlank()) {
                icon.visibility = View.VISIBLE
                Glide.with(icon).load(logo).into(icon)
            } else {
                icon.visibility = View.GONE
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val data: JSONObject = dataList[position]
        holder.bindData(data, position)
    }

    override fun getItemCount(): Int {
        return dataList.size
    }
}